package cd.cdyb.sms.interceptor;

import cd.cdyb.sms.service.WhiteListService;
import cd.cdyb.sms.utils.JacksonUtilPlus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WhitelistInterceptor implements HandlerInterceptor {


    private List<String> whitelist;

    @Value("classpath:exception.properties")
    private Resource configFile;

    public WhitelistInterceptor(WhiteListService whiteListService) {
        this.whitelist = whiteListService.findWhiteAddressList();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        if (requestURI.contains("message/pmall/sendMessageWithParam") || requestURI.contains("message/pmall/sendMessage")){
            String clientIP = getClientIP(request);
            if (!whitelist.contains(clientIP)) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access denied");
                return false;
            }
        }
        return true;
    }



    public String getClientIP(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }


}
